<template>
  <div class="wrapper">
    <dx-header-bar :title="productNo"></dx-header-bar>
    <div class="content-wrapper">
      <md-field>
        <md-field-item
          title="指标名称"
          arrow="arrow-right"
          align="right"
          :content="indexValue"
          @click.native="isIndexSelectorShow = true"/>
        <md-field-item
          title="开始时间"
          arrow="arrow-right"
          align="right"
          :content="startTime"
          @click.native="isStartTimePickerShow = true"/>
        <md-field-item
          title="结束时间"
          arrow="arrow-right"
          align="right"
          :content="endTime"
          @click.native="isEndTimePickerShow = true"/>
        <div class="btn-box">
          <md-button size="small" plain
                     v-for="(item, index) in timeRangeButtons" :key="index"
                     :type="index === timeRangeButtonIndex ? 'primary' : 'default'"
                     @click="onChangeTimeRange(index)">
            {{item.name}}
          </md-button>
          <md-button size="small" type="primary" @click="loadData">查询</md-button>
        </div>
      </md-field>
      <dx-e-chart class="chart" ref="chartCpt"
                  :color="['#90c118', '#2f86f6']"
                  :x-axis-data="chartXAxisData"
                  :series="chartSeries">
      </dx-e-chart>
      <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <thead>
        <tr>
          <th width="40%">时间</th>
          <th v-for="(item, index) in performanceList" :key="index">{{item.name}}</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(data, index) in dataList" :key="index">
          <td>
            {{data.TIME_STAMP}}
          </td>
          <td v-for="(item, count) in performanceList" :key="count">
            {{data[item.key]}}
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <md-selector title="指标名称" max-height="320px"
                 :data="indexList" :default-value="indexValue"
                 v-model="isIndexSelectorShow"
                 @choose="onIndexChoose"/>
    <md-date-picker
      ref="startTimePicker"
      v-model="isStartTimePickerShow"
      type="custom"
      title="开始时间"
      :custom-types="['yyyy', 'MM','dd', 'hh', 'mm']"
      :default-date="startDate"
      @confirm="onStartTimeConfirm"/>
    <md-date-picker
      ref="endTimePicker"
      v-model="isEndTimePickerShow"
      type="custom"
      title="结束时间"
      :custom-types="['yyyy', 'MM','dd', 'hh', 'mm']"
      :default-date="endDate"
      @confirm="onEndTimeConfirm"/>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  Dialog,
  Toast,
  Field,
  Selector,
  InputItem,
  FieldItem,
  DatePicker,
  Button
} from 'mand-mobile';
import { DxHeaderBar, DxEChart } from '@/components';
import { getPerf } from '@/api/resource';
import moment from 'moment';

function dateFormat(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
}

export default {
  components: {
    DxHeaderBar,
    DxEChart,
    [Field.name]: Field,
    [Selector.name]: Selector,
    [InputItem.name]: InputItem,
    [FieldItem.name]: FieldItem,
    [DatePicker.name]: DatePicker,
    [Button.name]: Button
  },
  data() {
    return {
      type: this.$route.query.type,
      productNo: this.$route.query.productNo,
      isIndexSelectorShow: false,
      index: 0,
      indexValue: '',
      indexList: [],
      performanceList: [],
      timeRangeButtons: [],
      timeRangeButtonIndex: -1,
      isStartTimePickerShow: false,
      isEndTimePickerShow: false,
      startDate: new Date(),
      endDate: new Date(),
      startTime: '',
      endTime: '',
      dataList: [],
      chartXAxisData: [],
      chartSeries: []
    };
  },
  mounted() {
    this.initData();
  },
  beforeRouteLeave(to, from, next) {
    if (from.query.from === 'home') {
      // eslint-disable-next-line
      to.query.isOnlyShowPerf = true;
    }
    next();
  },
  methods: {
    initData() {
      this.initIndexList();
      this.initTime();
    },
    initIndexList() {
      const type = this.type;
      // 初始化指标列表及默认指标
      let indexList = [];
      if (type === 'net' || type === 'trans') {
        indexList = [
          {
            value: '流量',
            text: '流量',
            list: [
              { name: '上行流量(MB)', key: 'PORT_IN', chartType: 'bar' },
              { name: '下行流量(MB)', key: 'PORT_OUT', chartType: 'bar' }
            ]
          },
          {
            value: '利用率',
            text: '利用率',
            list: [
              { name: '上行带宽利用率均值(%)', key: 'IN_UTILITY', chartType: 'line' },
              { name: '下行带宽利用率均值(%)', key: 'OUT_UTILITY', chartType: 'line' }
            ]
          }
        ];
      } else if (type === 'speech') {
        indexList = [
          {
            value: '通话时长',
            text: '通话时长',
            list: [
              { name: '通话时长(分钟)', key: 'CHARGE_LENGTH', chartType: 'line' }
            ]
          },
          {
            value: '国际港澳台时长',
            text: '国际港澳台时长',
            list: [
              { name: '国际港澳台时长(分钟)', key: 'OTHER_NET_LENGTH', chartType: 'line' }
            ]
          }
        ];
      } else if (type === 'sms') {
        indexList = [
          {
            value: '发送量',
            text: '发送量',
            list: [
              { name: '发送量', key: 'DOWN_SUBMIT_TOTAL_COUNT', chartType: 'line' }
            ]
          },
          {
            value: '发送失败数',
            text: '发送失败数',
            list: [
              { name: '发送失败数', key: 'SUC_DOWN_FAIL_COUNT', chartType: 'line' }
            ]
          },
          {
            value: '成功率',
            text: '成功率',
            list: [
              { name: '成功率(%)', key: 'SUC_DOWN_SUBMIT_UTIL', chartType: 'line' }
            ]
          }
        ];
      } else if (type === 'apn') {
        indexList = [
          {
            value: '流入流量',
            text: '流入流量',
            list: [
              { name: '流入流量(MB)', key: 'INCOCTPGW_APN', chartType: 'line' }
            ]
          },
          {
            value: '流出流量',
            text: '流出流量',
            list: [
              { name: '流出流量(MB)', key: 'OUTOCTPGW_APN', chartType: 'line' }
            ]
          },
          {
            value: 'PDP激活成功率',
            text: 'PDP激活成功率',
            list: [
              { name: 'PDP激活成功率(%)', key: 'SUCC4G_RATE', chartType: 'line' }
            ]
          },
          {
            value: '激活请求次数',
            text: '激活请求次数',
            list: [
              { name: '激活请求次数', key: 'CRE_REQ_CNT', chartType: 'line' }
            ]
          },
          {
            value: '激活请求成功次数',
            text: '激活请求成功次数',
            list: [
              { name: '激活请求成功次数', key: 'REQ_SUCC_CNT', chartType: 'line' }
            ]
          },
          {
            value: '在线用户数',
            text: '在线用户数',
            list: [
              { name: '在线用户数', key: 'APN_ONLINE_TERM_USER_CNT', chartType: 'line' }
            ]
          }
        ];
      }
      this.indexList = indexList;
      this.onIndexChoose(indexList[0]);
    },
    initTime() {
      // 初始化时间
      if (this.type === 'speech') {
        // 默认最近3个月 、最近6个月、最近12个月
        this.timeRangeButtons = [
          { name: '最近3个月', value: 3, unit: 'months' },
          { name: '最近6个月', value: 6, unit: 'months' },
          { name: '最近12个月', value: 12, unit: 'months' }
        ];
      } else {
        // 默认最近1小时 最近1小时、最近12小时、最近24小时
        this.timeRangeButtons = [
          { name: '最近1小时', value: 2, unit: 'hours' },
          { name: '最近12小时', value: 12, unit: 'hours' },
          { name: '最近24小时', value: 24, unit: 'hours' }
        ];
      }
      const index = 0;
      this.timeRangeButtonIndex = index;
      this.onChangeTimeRange(index);
    },
    onChangeTimeRange(index) {
      this.timeRangeButtonIndex = index;
      if (index !== -1) {
        const { value, unit } = this.timeRangeButtons[index];
        this.setStartTime(value, unit);
        this.setEndTime();
        this.loadData();
      }
    },
    setStartTime(value, unit) {
      // eslint-disable-next-line
      this.startDate = moment().subtract(value, unit)._d;
      this.startTime = dateFormat(this.startDate);
    },
    setEndTime() {
      this.endDate = new Date();
      this.endTime = dateFormat(this.endDate);
    },
    onStartTimeConfirm() {
      const time = this.$refs.startTimePicker.getFormatDate();
      const after = moment(time).isBefore(this.endTime, 'second');
      if (!after) {
        Dialog.alert({
          title: '提示',
          content: '开始时间不能大于结束时间',
          confirmText: '确定'
        });
        return;
      }
      this.timeRangeButtonIndex = -1;
      this.startTime = moment(time, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm:ss');
    },
    onEndTimeConfirm() {
      const time = this.$refs.endTimePicker.getFormatDate();
      const before = moment(time).isBefore(this.startTime, 'second');
      // 判断结束时间是否在开始时间之前
      if (before) {
        Dialog.alert({
          title: '提示',
          content: '结束时间不能小于开始时间',
          confirmText: '确定'
        });
        return;
      }
      this.timeRangeButtonIndex = -1;
      this.endTime = moment(time, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm:ss');
    },
    onIndexChoose({ value }) {
      this.indexValue = value;
      this.index = this.indexList.findIndex(item => item.value === value);
      this.performanceList = this.indexList[this.index].list;
      this.extracData();
    },
    loadData() {
      this.$refs.chartCpt.showLoading();
      const params = {
        type: this.type,
        productNo: this.productNo,
        // productNo: '1101300047636071',
        // startTime: '2019-04-19 00:45:00',
        // endTime: '2019-04-20 00:45:00'
        startTime: this.startTime,
        endTime: this.endTime
      };
      getPerf(params).then(result => {
        const datas = result.data.datas;
        if (datas instanceof Array && datas.length) {
          this.dataList = datas.reverse();
        } else {
          Dialog.alert({
            title: '提示',
            content: '没有找到性能数据',
            confirmText: '确定'
          });
        }
        this.extracData();
      }).catch(() => {
        Toast.failed('数据加载失败');
        this.$refs.chartCpt.hideLoading();
      });
    },
    extracData() {
      const performanceList = this.performanceList;
      const xAxisData = [];
      const seriesData = performanceList.map(item => ({
        name: item.name,
        type: item.chartType,
        key: item.key,
        data: []
      }));
      this.dataList.forEach(data => {
        xAxisData.push(data.TIME_STAMP.substr(11, 5));
        seriesData.forEach(item => {
          item.data.push(data[item.key]);
        });
      });
      this.chartXAxisData = [xAxisData];
      this.chartSeries = seriesData;
      this.$nextTick(() => {
        this.$refs.chartCpt.updateChart();
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
  .wrapper
    display: flex
    flex-direction: column
    height: 100%

  .content-wrapper
    flex: 1
    overflow-y: auto
    font-size: 28px

  .md-field
    padding: 0 20px

  .chart
    height: 400px
    width: 100%

  .btn-box
    display: flex
    padding: 20px 0

    .md-button
      margin-right: 20px

      &:last-of-type
        margin-right: 0

      &.selected
        border-color: theme-color
        color: theme-color

  table
    line-height: 38px
    background: #fff
    text-align: center
    font-size: 28px

  th, td
    padding: 20px 8px
    border-bottom: 1px solid #eee
    border-right: 1px solid #eee

    &:last-of-type
      border-right: none

    &.is-link
      color: theme-color

  thead
    tr
      background: #f5f9fe

  tbody
    tr:nth-of-type(odd)
      background: #fff

    tr:nth-of-type(even)
      background: #f9f9f9
</style>
